﻿using System;
using System.Windows;
using System.Windows.Media.Imaging;
using DAL.Clipboard.ClipboardListener;

namespace DAL.Clipboard
{
    public class ClipboardAccess : IClipboardAccess
    {
        protected const string HtmlFormatString = "HTML Format";
        protected const string RichTextFormatString = "Rich Text Format";
        protected ClipboardChangeListener ClipboardChangeListener;

        public ClipboardAccess()
        {
            ClipboardChangeListener = new ClipboardChangeListener();
            ClipboardChangeListener.ClipboardChanged += delegate { ClipboardChanged(this, EventArgs.Empty); };
        }

        #region IClipboardAccess Members

        public event EventHandler ClipboardChanged;
        public bool RaiseChangeEvents { get { return ClipboardChangeListener.IsEnabled; } set { ClipboardChangeListener.IsEnabled = value; } }

        public ClipboardContent GetClipboardContent()
        {
            var ret = new ClipboardContent
            {
                Image = GetItem<BitmapSource>(),
                Html = GetItem<string>(HtmlFormatString),
                Rtf = GetItem<string>(RichTextFormatString),
                Text = GetItem<string>(),
                Time = DateTime.Now,
            };

            if (ret.Image == null && ret.Html == null && ret.Rtf == null && ret.Text == null)
                return null;
            else
                return ret;
        }

        public void SetClipboardContent(ClipboardContent content)
        {
            var dataObj = new DataObject();

            if (content.Text != null)
                dataObj.SetText(content.Text, TextDataFormat.Text);

            if (content.Rtf != null)
                dataObj.SetText(content.Rtf, TextDataFormat.Rtf);

            if (content.Html != null)
                dataObj.SetText(content.Html, TextDataFormat.Html);

            if (content.Image != null)
                dataObj.SetImage(content.Image);

            System.Windows.Clipboard.SetDataObject(dataObj);
        }

        public void ClearClipboard()
        {
            System.Windows.Clipboard.Clear();
        }

        public void Dispose()
        {
            ClipboardChangeListener.Dispose();
        }

        #endregion

        protected T GetItem<T>(string format = null) where T : class
        {
            if (format == null)
                format = typeof(T).FullName;

            var dataObj = System.Windows.Clipboard.GetDataObject();
            if (dataObj == null) return null;

            return dataObj.GetDataPresent(format) ? dataObj.GetData(format) as T : null;
        }
    }
}
